package com.ruoyi.web.controller.gd;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDate;
import java.util.List;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.amazonaws.util.IOUtils;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.gd.fj.domain.bo.ZFujianBo;
import com.ruoyi.gd.fj.domain.vo.ZFujianVo;
import com.ruoyi.gd.fj.service.IZFujianService;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.gd.todo.domain.vo.zTodoVo;
import com.ruoyi.gd.todo.domain.bo.zTodoBo;
import com.ruoyi.gd.todo.service.IzTodoService;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 待办内容
 *
 * @author ruoyi
 * @date 2024-11-19
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/gd/todo")
public class zTodoController extends BaseController {

    private final IzTodoService izTodoService;

    @Value("${upload.todo}")
    private String uploadPath;

    @Autowired
    private IZFujianService fujianService;

    /**
     * 查询待办内容列表
     */
    @GetMapping("/list")
    public List<zTodoVo> list(zTodoBo bo) {
        return izTodoService.queryList(bo);
    }

    /**
     * 导出待办内容列表
     */
    @Log(title = "待办内容", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(zTodoBo bo, HttpServletResponse response) {
        List<zTodoVo> list = izTodoService.queryList(bo);
        ExcelUtil.exportExcel(list, "待办内容", zTodoVo.class, response);
    }

    /**
     * 获取待办内容详细信息
     *
     * @param id 主键
     */
    @GetMapping("/{id}")
    public R<zTodoVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable String id) {
        return R.ok(izTodoService.queryById(id));
    }

    /**
     * 新增待办内容
     */
    @Log(title = "待办内容", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody zTodoBo bo) {
        return toAjax(izTodoService.insertByBo(bo));
    }

    /**
     * 修改待办内容
     */
    @Log(title = "待办内容", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody zTodoBo bo) {
        return toAjax(izTodoService.updateByBo(bo));
    }

    /**
     * 删除待办内容
     *
     * @param ids 主键串
     */
    @Log(title = "待办内容", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable String[] ids) {
        return toAjax(izTodoService.deleteWithValidByIds(Arrays.asList(ids), true));
    }

    /**
     * 批量上传
     */
    @PostMapping("/file/batchUpload")
    public ResponseEntity<Object> batchUpload(@RequestParam("file") MultipartFile file) throws Exception {
        // 遍历附件
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("File is empty.");
        }
        // 获取文件原名
        String originalFilename = file.getOriginalFilename();
        // 判断当前地址是否存在，不存在则创建
        Path filePath = Paths.get(uploadPath);
        // 判断路径是否存在
        if (!Files.exists(filePath)) {
            // 如果路径不存在，则尝试创建目录（假设uploadPath是指向目录的）
            Files.createDirectories(filePath);
        }
        // 获取后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 重新生成文件名
        String fileName = IdUtil.simpleUUID() + suffix;
        LocalDate currentDate = LocalDate.now();
        // 分别获取年、月、日
        int year = currentDate.getYear();
        int monthValue = currentDate.getMonthValue();
        int dayOfMonth = currentDate.getDayOfMonth();
        // 生成Excel路径
        String suffixPath = "/" + year + "/" + monthValue + "/" + dayOfMonth + "/";
        // 判断当前文件路径的文件夹是否存在，不存在则创建
        if (!Files.exists(Paths.get(uploadPath + suffixPath))) {
            // 路径不存在，尝试创建
            try {
                Files.createDirectories(Paths.get(uploadPath + suffixPath));
            } catch (Exception e) {
                System.err.println("创建目录时出错: " + e.getMessage());
            }
        }
        // 构建新的文件名和目标路径
        Path targetLocation = Paths.get(uploadPath + suffixPath + fileName);
        // 将文件保存到指定目录
        Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
        // 上传后将文件数据添加到文件数据库
        ZFujianBo fujianBo = new     ZFujianBo();
        fujianBo.setFjid(IdUtil.simpleUUID());  //设置附件id
        fujianBo.setFjname(originalFilename);   //设置附件名称
        fujianBo.setFjpath(suffixPath + fileName);  //设置附件路径
        fujianBo.setFjtype(suffix);
        fujianService.insertByBo(fujianBo);
        // 将上传的附件返回
        return ResponseEntity.ok(fujianBo);
    }

    /**
     * 获取文件流
     * @param id
     * @return
     * @throws IOException
     */
    @GetMapping(value = "/getFj/{id}")
    public byte[] getPdf(@PathVariable String id) throws IOException {
        // 1.通过id获取当前附件信息
        ZFujianVo fujianVo = fujianService.queryById(id);
        // 2.获取附件路径
        String path = uploadPath + fujianVo.getFjpath();
        // 3.获取文件
        File file = new File(path);
        FileInputStream inputStream = new FileInputStream(file);
        return IOUtils.toByteArray(inputStream);
    }

    /**
     * 更改状态
     */
    @Log(title = "待办内容", businessType = BusinessType.UPDATE)
    @PutMapping("/updateStatus")
    public R<Boolean> updateStatus(@RequestBody zTodoBo bo) {
        return R.ok("修改成功！",izTodoService.updateStatus(bo));
    }

    /**
     * 通过文员角色查询文员用户
     */
    @Log(title = "待办内容", businessType = BusinessType.OTHER)
    @GetMapping("/queryWyUser")
    public List<SysUser> queryWyUser() {
        return izTodoService.queryWyUser();
    }

    /**
     * 重置任务
     */
    @Log(title = "待办内容", businessType = BusinessType.OTHER)
    @PutMapping("/resetTodo/{id}")
    public R<Boolean> resetTodo(@PathVariable String id) {
        return R.ok("退回成功！", izTodoService.resetTodo(id));
    }


}
